<template>
  <div style="width: 100%">
    <div class="article clearfix">
      <div
        v-show="!state.isLoading"
        :style="{ width: state.isMobileOrPc ? '100%' : '75%' }"
        class="article-left fl"
      >
        <div class="header">
          <h1 class="title">{{ state.articleDetail.title }}</h1>
          <div class="author">
            <div class="avatar">
              <img class="auth-logo" src="../assets/userLogo.jpeg" alt="图片" />
            </div>
            <div class="info">
              <span class="name">
                <span>{{ state.articleDetail.author }}</span>
              </span>
              <div
                props-data-classes="user-follow-button-header"
                data-author-follow-button=""
              />
              <div class="meta">
                <span class="publish-time">
                  {{
                    state.articleDetail.create_time
                      ? state.articleDetail.create_time
                      : ""
                  }}
                </span>
                <span class="wordage">
                  字数 {{ state.articleDetail.numbers }}
                </span>
                <span class="views-count">
                  阅读 {{ state.articleDetail.meta.views }}
                </span>
                <span class="comments-count">
                  评论 {{ state.articleDetail.meta.comments }}
                </span>
                <span class="likes-count">
                  喜欢 {{ state.articleDetail.meta.likes }}
                </span>
              </div>
            </div>
            <div class="tags" title="标签">
              <el-tag
                size="mini"
                v-for="tag in state.articleDetail.tags"
                :key="tag.id"
                class="tag"
                type="success"
                >{{ tag }}</el-tag
              >
            </div>
            <span class="clearfix" />
          </div>
        </div>
        <div class="content">
          <div
            id="content"
            class="article-detail"
            v-html="state.articleDetail.content"
          ></div>
        </div>
        <div class="heart">
          <el-button
            type="danger"
            size="large"
            icon="heart"
            :loading="state.isLoading"
            @click="likeArticle"
          >
            点赞
          </el-button>
        </div>
        <div class="comment">
          <el-input
            placeholder="文明社会，理性评论"
            type="textarea"
            v-model="state.content"
          ></el-input>
          <el-button
            style="margin-top: 15px"
            type="primary"
            :loading="state.btnLoading"
            @click="handleAddComment"
            >发 送</el-button
          >
        </div>
        <CommentList
          v-if="!state.isLoading"
          :numbers="state.articleDetail.meta.comments"
          :list="state.articleDetail.comments"
          :article_id="state.articleDetail.id"
          @refreshArticle="refreshArticle"
        />
      </div>
      <div
        v-if="!state.isMobileOrPc"
        style="width: 23%"
        class="article-right fr anchor"
        v-html="state.articleDetail.toc"
      ></div>
      <!-- <LoadingCustom v-if="state.isLoading"></LoadingCustom> -->
    </div>
  </div>
</template>

<script setup lang="ts">
//代码高亮
// import highlight from "highlight.js";
// import "highlight.js/styles/default.css";
// import marked  from 'marked'
import showdown from "showdown";
import { ElMessage } from "element-plus";
import { GetArtiDetail, AddComment,LikeArticle } from "../api/api";
import CommentList from "../components/CommentList.vue";
import { ArtiDetailParams, ArtiDetailInfo } from "../type/index";
import { reactive, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
const state = reactive({
  btnLoading: false,
  isLoadEnd: false,
  isLoading: false,
  //   isMobileOrPc: isMobileOrPc(),
  params: {
    id: "",
    type: 1, //文章类型 => 1: 普通文章，2: 简历，3: 管理员介绍
  } as ArtiDetailParams,
  content: "",
  articleDetail: {
    toc: "",
    author: "biaochenxuying",
    category: [],
    comments: [],
    create_time: "",
    desc: "",
    content: "",
    id: -1,
    img_url: "",
    numbers: 0,
    keyword: [],
    like_users: [],
    meta: { views: 0, likes: 0, comments: 0 },
    origin: 0,
    state: 1,
    tags: [],
    title: "",
    update_time: "",
  } as ArtiDetailInfo,
  cacheTime: 0, // 缓存时间
  times: 0, //评论次数
  likeTimes: 0, // 点赞次数
});
const handleSearch = async (): Promise<void> => {
  state.isLoading = true;
  console.log("123");
  const res = await GetArtiDetail(state.params);

  state.isLoading = false;
  console.log("res:", res);
  state.articleDetail = res.data;
  console.log(res.data.content);
  const converter = new showdown.Converter();
  res.data.content = converter.makeHtml(res.data.content);
  console.log(converter.makeHtml(res.data.content));
  //  console.log(state.articleDetail)
  //  console.log(state.articleDetail.meta.comments)
  //   console.log(state.articleDetail.comments)
  // const article = markdown.marked(data.content);
  // article.then((res: any) => {
  //   state.articleDetail.content = res.content;
  //   state.articleDetail.toc = res.toc;
  // });
  // let keyword = data.keyword.join(",");
  // let description = data.desc;
  // let title = data.title;
  // document.title = title;
  // document.querySelector("#keywords").setAttribute("content", keyword);
  // document
  //   .querySelector("#description")
  // .setAttribute("content", description);
};
const refreshArticle = (): void => {
  // handleSearch();
};
const likeArticle = async (): Promise<void> => {
  if (!state.articleDetail.id) {
    ElMessage({
      message: "该文章不存在！",
      type: "warning",
    });
    return;
  }
  if (state.likeTimes > 0) {
    ElMessage({
      message: "您已经点过赞了！悠着点吧！",
      type: "warning",
    });
    return;
  }
  let user_id;
  if (window.localStorage.userInfo) {
    let userInfo = JSON.parse(window.localStorage.userInfo);
    user_id = parseInt(userInfo._id);
  } else {
    ElMessage({
      message: "登录才能点赞，请先登录！",
      type: "warning",
    });
    return;
  }
  console.log("article_id",state.articleDetail.id,"user_id",user_id)
  let params = {
    article_id: state.articleDetail.id,
    user_id,
  };
  state.isLoading = true;
  const res= await LikeArticle(params);
  console.log("res:",res)
  state.isLoading = false;
  state.likeTimes++;
  ++state.articleDetail.meta.likes;
  ElMessage({
    message: "操作成功",
    type: "success",
  });
};
const handleAddComment = async (): Promise<void> => {
  if (!state.articleDetail.id) {
    ElMessage({
      message: "该文章不存在！",
      type: "error",
    });
    return;
  }

  if (state.times > 2) {
    ElMessage({
      message: "您今天评论的次数已经用完，明天再来评论吧！",
      type: "warning",
    });
    return;
  }
  let now = new Date();
  let nowTime = now.getTime();
  if (nowTime - state.cacheTime < 4000) {
    ElMessage({
      message: "您评论太过频繁，1 分钟后再来留言吧！",
      type: "warning",
    });
    return;
  }

  if (!state.content) {
    ElMessage({
      message: "请输入内容!",
      type: "warning",
    });
    return;
  }
  let user_id = -1;
  if (window.localStorage.userInfo) {
    let userInfo = JSON.parse(localStorage.getItem("userInfo"));
    user_id = parseInt(userInfo._id);
  } else {
    ElMessage({
      message: "登录才能评论，请先登录！",
      type: "warning",
    });
    return;
  }
  state.btnLoading = true;
  //console.log( state.articleDetail.id)
  const res = await AddComment({
    article_id: state.articleDetail.id,
    user_id,
    contents: state.content,
  });
  console.log(res);
  state.btnLoading = false;
  state.times++;
  state.cacheTime = nowTime;
  state.content = "";
  ElMessage({
    message: "操作成功",
    type: "success",
  });
  handleSearch();
};

onMounted(() => {
  // state.articleDetail = {
  //     toc: "111111111111garterhrth2346g2heh25g45",
  //     _id: "22",
  //     author: "cyw",
  //     category: [],
  //     comments: [
  //       {
  //         content: "1342353425",
  //         create_time: "2023-12-34",
  //         likes: 1,
  //         state: 1,
  //         to_user: {},
  //         user: {
  //           user_id: "12",
  //           name: "35",
  //           avatar: "ffff",
  //           type: 12,
  //         },
  //         _id: "123",
  //       },
  //     ],
  //     create_time: "2022-09-23",
  //     desc: "ddddddd",
  //     content:
  //       "哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈或或或或或或或或",
  //     id: 12,
  //     img_url: "http:////",
  //     numbers: 23445,
  //     keyword: ["llll"],
  //     like_users: ["ab", "fdf"],
  //     meta: {
  //       views: 0,
  //       likes: 0,
  //       comments: 2,
  //     },
  //     origin: 12,
  //     state: 35,
  //     tags: [{ name: "354" }, { name: "46" }],
  //     title: "12434",
  //     update_time: "2022-10-12",
  //   };
  console.log("444");
  state.params.id = route.query.article_id as string;
  // if (route.path === "/about") {
  //   state.params.type = 3;
  // }

  handleSearch();
});
</script>

<style scoped lang="less">
.anchor {
  display: block;
  position: sticky;
  top: 213px;
  margin-top: 213px;
  border-left: 1px solid #eee;
  .anchor-ul {
    position: relative;
    top: 0;
    max-width: 250px;
    border: none;
    -moz-box-shadow: 0 0px 0px #fff;
    -webkit-box-shadow: 0 0px 0px #fff;
    box-shadow: 0 0px 0px #fff;

    li.active {
      color: #009a61;
    }
  }
  a {
    color: #333;
  }
}
.article {
  width: 100%;
  .header {
    .title {
      margin: 20px 0 0;
      text-align: center;
      font-size: 34px;
      font-weight: bold;
    }
    .author {
      position: relative;
      margin: 30px 0 40px;
      padding-left: 50px;
      .avatar {
        position: absolute;
        left: 0;
        top: 0;
        width: 48px;
        height: 48px;
        vertical-align: middle;
        display: inline-block;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }
      .info {
        float: left;
        vertical-align: middle;
        // display: inline-block;
        margin-left: 8px;
        a {
          color: #333;
        }
      }
      .name {
        margin-right: 3px;
        font-size: 16px;
        vertical-align: middle;
      }
      .meta {
        margin-top: 5px;
        font-size: 12px;
        color: #969696;
        span {
          padding-right: 5px;
        }
      }
      .tags {
        float: right;
        padding-top: 15px;
        // padding-right: 20px;
        .tag {
          // padding: 0 10px;
          margin-left: 5px;
          border-right: 2px solid #eee;
        }
      }
    }
  }
  .content {
    min-height: 300px;
  }
}
.heart {
  height: 60px;
  text-align: center;
  margin: 50px;
}
.loader {
  color: rgb(226, 44, 44);
  text-align: center;
  padding: 50px;
  font-size: 16px;
}
.clearfix {
  clear: both;
}
</style>
